<?php
namespace addons\vote\controllers;
use addons\member\models\Member;
use addons\vote\models\VoteLogModel;
use controllers\HomeBase;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use system\Route\Request;
use system\Tool\Upload;

class api extends HomeBase {
	protected $model = '';
	// jwt的key
	protected $jwtKey = 'vote_myclass_php';

	/**
	 * 首页接口
	 * @param string $keyword
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-13 下午4:36
	 * @return string
	 */
	public function index($keyword = ''){
		$uid = $this->getUid();
		if (!is_numeric($uid)){
			return $uid;
		}
		$news = $this->callApi('news:api/getNews');
		$model = new Member();
		$map = $listMap = ['state' => 1];
		if ($keyword){
			if (is_numeric($keyword)){
				$listMap['number'] = intval($keyword);
			}else{
				$listMap['name'] = ['like' , $keyword];
			}
		}
		$page = self::$get['page'] ? self::$get['page'] : 1;
		$pageSize = 10;
		$list = $model->where($listMap)->field('name,user_avatar,id as aid,ticket,number')->order('ticket desc,id asc')->limit($page , $pageSize)->select();
		foreach ($list as &$val){
			$val['user_avatar'] = $this->getImage($val['user_avatar']);
			$val['number'] = $this->showNumber($val['number']);
		}
		$ticket = $model->where($map)->sum('ticket');
		$count = $model->where($map)->count();
		$redisKeys = 'user_views';
		$redis = getRedis();
		$views = $redis->sCard($redisKeys);
		$data = [
			'count' => [
				'people' => $count , // 总参加人数
				'ticket' => $ticket , // 总票数
				'view' => $views ? $views : 0, // 浏览人数
			] ,
			'list' => $list ,
			'news' => $news['data'] ,
			'has' => $this->hasPage($count , $pageSize)
		];
		// 增加浏览数
		$key = date('Ymd') . '_' . $uid;
		if(!$redis->sIsMember($redisKeys , $key)){
			$redis->sAdd($redisKeys , $key);
		}
		$isWrite = $this->isWrite($uid);
		$data['is_write'] = $isWrite;
		return success($data);
	}

	/**
	 * 发起投票
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-09 下午8:07
	 */
	public function vote(){
		$uid = $this->getUid();
		if (!is_numeric($uid)){
			return $uid;
		}
		$touid = trim(self::$post['to']);
		if (!is_numeric($touid)){
			return error('无效的投票信息');
		}
		$remark = trim(self::$post['remark']);
		if (!$remark){
			return error('请输入您的投票原因');
		}
		if ($uid == $touid){
			return error('不能给自己投票哟');
		}
		$ticket = 1;
		$model = new VoteLogModel();
		if(!$model->ticketValid($uid , $touid , '你的剩余可用票数不足')){
			return error($model->error);
		}
		$model->startTransaction();
		// 增加一条记录
		$status = $model->insert([
			'uid' => $uid ,
			'touid' => $touid ,
			'comment' => $remark ,
			'create_time' => time() ,
		]);
		if (!$status){
			$model->rollback();
			return error('投票失败');
		}
		// 增加被投票人的票数
		$ticketState = $model->updateUserTicket($touid , $uid , $ticket);
		if (!$ticketState){
			$model->rollback();
			return error('投票失败!');
		}
		$model->commit();
		return success('投票成功');
	}

	/**
	 * 详情页接口
	 * @return int|string
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-13 下午4:51
	 */
	public function detail(){
		$uid = $this->getUid();
		if (!is_numeric($uid)){
			return $uid;
		}
		$id = self::$get['id'];
		if (!is_numeric($id)){
			return error('无效的信息');
		}
		$model = new Member();
		$find = $model->where(['id' => $id])->field('name,deparent_id,number,ticket,user_avatar')->find();
		if (!$find){
			return error('信息不存在');
		}
		$logModel = new VoteLogModel();
		$find['number'] = $this->showNumber($find['number']);
		$find['user_avatar'] = $this->getImage($find['user_avatar']);
		$find['deparent'] = $logModel->deparents[$find['deparent_id']];
		unset($find['deparent_id']);
		$find['rank'] = rank::getRank($id);
		$find['isVote'] = $logModel->isVote($uid);
		$find['isSelf'] = $uid == $id;
		return success([
			'find' => $find
		]);
	}

	/**
	 * 新闻详情
	 * @return string
	 * @throws \system\MyError
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-13 下午7:00
	 */
	public function newsDetail(){
		$id = self::$get['id'];
		if (!is_numeric($id)){
			return error('无效的数据');
		}
		$res = $this->callApi('news:api/detail' , ['id' => $id]);
		if ($res['code'] == 0){
			return success($res['data']);
		}
		return error($res['msg']);
	}

	/**
	 * 我的投票列表
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-09 下午8:21
	 */
	public function voteList(){
		$uid = $this->getUid();
		if (!is_numeric($uid)){
			return $uid;
		}
		$page = 1;
		$pageSize = 10;
		$type = 1; // 类型值  1 我的 2 别人的
		$model = new VoteLogModel();
		$map = [];
		if ($type == 1){
			// 我的投票记录
			$keyField = 'uid';
		}else{
			// 别人投给我的
			$keyField = 'touid';
		}
		$map['a.' . $keyField] = $uid;
		$on = 'm.id = a.' . $keyField;
		$list = $model->where($map)->alias('a')->join('@member as m' , $on)->limit($page , $pageSize)->field('a.create_time,a.comment,m.nickname,m.avatar')->select();
		$count = $model->alias('a')->join('@member as m' , $on)->where($map)->count('a.id');
		foreach ($list as &$val){
			$val['create_time'] = timeFormat($val['create_time']);
		}
		return success(['list' => $list , 'has' => $this->hasPage($count , $list , $pageSize)]);
	}

	/**
	 * 排行榜单
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-09 下午8:36
	 */
	public function rank(){
		$uid = $this->getUid();
		if (!is_numeric($uid)){
			return $uid;
		}
		$model = new Member();
		$page = 1;
		$pageSize = 100;
		$map = [
			'state' => 1 ,
			'ticket' => ['gt' , 0] ,
		];
		$list = $model->where($map)->field('number,name,user_avatar,ticket,id')->limit($page , $pageSize)->order('ticket desc')->select();
		$count = $model->where($map)->count();
		$rank = rank::getRank($uid);
		foreach ($list as $key => &$val){
			$val['user_avatar'] = $this->getImage($val['user_avatar']);
			$val['rank'] = $key + 1;
			$val['number'] = $this->showNumber($val['number']);
		}
		// 我的排名信息
		$self = $model->where(['id' => $uid])->field('ticket_put,ticket,name,user_avatar,number')->find();
		if ($self){
			$self['user_avatar'] = $this->getImage($self['user_avatar']);
			$self['rank'] = $rank > 99 ? '99+' : $rank;
		}
		$isWrite = $this->isWrite($self);
		unset($self['number']);
		return success([
			'list' => $list ,
			'has' => $this->hasPage($count , $pageSize) ,
			'self' => $self ,
			'is_write' => $isWrite ,
		]);
	}

	//	public function session(Request $request){
	//		$app = self::getApp();
	//		$code = $request->post('code');
	//		$res = $app->auth->session($code);
	//		return success($res);
	//	}

	/**
	 * 登录一个用户
	 * @param Request $request
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-11 下午9:34
	 */
	public function login(Request $request){
		$app = self::getApp();
		$code = $request->post('code');
		$iv = $request->post('iv');
		$encryptedData = $request->post('data');
		$res = $app->auth->session($code);
		if (!isset($res['openid']) || !isset($res['session_key'])){
			return error('登录失败，请重试');
		}
		$decryptedData = $app->encryptor->decryptData($res['session_key'], $iv, $encryptedData);
		if (!$decryptedData){
			return error('登录失败，请重试!');
		}
		$nickname = $decryptedData['nickName'];
		$avatar = $decryptedData['avatarUrl'];
		$gender = $decryptedData['gender'];
		$openid = $res['openid'];
		$model = new Member();
		$map = ['account' => $openid , 'platform' => 3];
		$find = $model->where($map)->find();
		$save = [
			'avatar' => $avatar ,
			'nickname' => $nickname ,
			'sex' => $gender ,
		];
		if (!$find){
			// 注册一个用户
			$save = array_merge($save , $map);
			$save['create_time'] = time();
			$save['version'] = $this->getVersion($request);
			$save['state'] = 1;
			$id = $model->insert($save);
			$isWrite = true;
		}else{
			// 现有的用户，更新头像信息
			$model->where(['id' => $find['id']])->update($save);
			$id = $find['id'];
			$isWrite = $this->isWrite($find);
		}
		return success([
			'token' => $this->getToken($id) ,
			'is_write' => $isWrite ,
		]);
	}

	/**
	 * 是否需要填写信息，为true，则需要
	 * @param $find
	 * @return bool
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-16 下午8:39
	 */
	protected function isWrite($find){
		if (is_numeric($find)){
			$model = new Member();
			$find = $model->getFind($find);
		}
		return !($find['user_avatar'] && $find['name'] && $find['number']);
	}

	/**
	 * 获取个人详细信息
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-13 下午3:06
	 */
	public function profile(){
		$uid = $this->getUid();
		if (!is_numeric($uid)){
			return $uid;
		}
		$memberModel = new Member();
		$find = $memberModel->where(['id' => $uid])->find();
		$user = [
			'avatar' => '' ,
			'number' => '' ,
			'deparent_id' => '' ,
			'name' => '' ,
			'write' => true ,
		];
		if ($find){
			$isNotWrite = !($find['number'] && $find['user_avatar'] && $find['name']);
			$user['avatar'] = !$find['user_avatar'] ? $find['user_avatar'] : $this->getImage($find['user_avatar']);
			$user['number'] = !$find['number'] ? $find['number'] : $this->showNumber($find['number']);
			$user['deparent_id'] = $find['deparent_id'];
			$user['name'] = $find['name'];
			$user['write'] = $isNotWrite;
		}
		$model = new VoteLogModel();
		$deparents = [];
		foreach ($model->deparents as $key => $val){
			$deparents[] = ['id' => $key , 'name' => $val];
		}
		return success([
			'depearent' => $deparents ,
			'find' => $user ,
		]);
	}

	/**
	 * 保存信息
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-13 上午11:39
	 */
	public function saveInfo(Request $request){
		$uid = $this->getUid();
		if (!is_numeric($uid)){
			return $uid;
		}
		$avatar = values('files.avatar');
		$data = $request->posts();
		$write = $data['write']; // true是完善资料，false为更新资料
		unset($data['avatar']);
		if ($write && !$avatar){
			return error('请上传头像');
		}
		if (!$data['number'] || !is_numeric($data['number'])){
			return error('请输入工号');
		}
		if (!$data['deparent_id']){
			return error('请选择部门');
		}
		if (!$data['name']){
			return error('请输入名称');
		}
		$model = new VoteLogModel();
		$status = $model->userNumberExists($data['number'] , $uid);
		if ($status){
			return error('工号已被占用');
		}
		$data = [
			'number' => $data['number'] ,
			'deparent_id' => $data['deparent_id'] ,
			'name' => $data['name'] ,
		];
		if ($avatar){
			$upload = new Upload($avatar);
			$uploads = $upload->upload();
			$info = $uploads['info'];
			$path = $info['path'];
			$data['user_avatar'] = $path;
		}
		$memberModel = new Member();
		$memberModel->where(['id' => $uid])->update($data);
		return success('保存成功');
	}

	/**
	 * 个人中心
	 * @return array|string
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-11 下午9:34
	 */
	public function ucenter(){
		$model = new Member();
		$uid = $this->getUid();
		if(!is_numeric($uid)){
			return $uid;
		}
		$find = $model->where(['id' => $uid])->find();
		if (!$find){
			return error('无效的用户' , 403);
		}
		$logModel = new VoteLogModel();
		return success([
			'avatar' => $this->getImage($find['user_avatar']) ,
			'nickname' => $find['name'] ,
			'deparent' => $logModel->deparents[$find['deparent_id']] ,
			'number' => $this->showNumber($find['number']) ,
			'ticket_my' => $find['ticket_put'] ,
			'free_ticket' => $logModel->maxTicket - $find['ticket_put'] ,
			'ticket_get' => $find['ticket'] ,
			'is_write' => $this->isWrite($find)
		]);
	}

	/**
	 * 显示工号
	 * @param $number
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-13 下午3:30
	 */
	protected function showNumber($number){
		if ($number < 10){
			return '00' . $number;
		}
		if ($number < 100){
			return '0' . $number;
		}
		return $number;
	}

	/**
	 * 获取用户信息
	 * @return int
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-11 下午9:22
	 */
	protected function getUid(){
		$code = self::$post['token'];
		if (!$code){
			return error('无效的token' , 403);
		}
		JWT::$leeway = 60;
		$decoded = JWT::decode($code, new Key($this->jwtKey, 'HS256'));
		$uid = $decoded->data->uid;
		if (!$uid){
			return error('无效的用户' , 403);
		}
		$model = new Member();
		$find = $model->where(['id' => $uid])->field('id')->find();
		if (!$find){
			return error('无效的用户' , 403);
		}
		return $uid;
	}

	/**
	 * 获取token
	 * @param int $uid
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-11 下午9:55
	 */
	protected function getToken($uid = 0){
		$payload = array(
			'iat' => time() ,
			'nbf' => time() ,
			'data' => [
				'uid' => $uid ,
			]
		);
		return JWT::encode($payload, $this->jwtKey , 'HS256');
	}

	/**
	 * 获取版本号
	 * @param $request
	 * @return mixed
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-11 下午9:58
	 */
	protected function getVersion($request){
		return $request->post('version' , 100);
	}

	/**
	 * 获取头像地址
	 * @param $image
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-11 下午10:03
	 */
	protected function getImage($image){
		if (!$image){
			return '';
		}
		return envg('img_host') . $image;
	}

	/**
	 * 是否有下一页
	 * @param $count
	 * @param $pageSize
	 * @return bool
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-11 下午9:10
	 */
	protected function hasPage($count , $pageSize){
		$maxPage = ceil($count / $pageSize);
		if ($maxPage > self::$get['page']){
			return true;
		}
		return false;
	}
}